package com.scqkxx.gamebox.activity.myself.loginutils;

import android.app.Activity;
import android.content.Context;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import android.widget.TextView;

import com.avos.avoscloud.AVCloud;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.FunctionCallback;
import com.scqkxx.gamebox.R;
import com.scqkxx.gamebox.activity.myself.SettingAboutUsActivity;
import com.scqkxx.gamebox.utils.AppInfoUtils;
import com.scqkzqtz.base.library.utils.ToastUtils;
import com.scqkzqtz.library.UpdateUtils;

import java.util.HashMap;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by zsx on 2018/8/14.
 */

public class LoginRequestUtils {
    public static final String SMSTYPE_LOGIN = "login";
    public static final String SMSTYPE_FORGET_PASSWORD = "forget_password";

    public static void requestSmsCode(Context context, String type, String phoneNubmber, @NonNull OnRequestListener onRequestListener) {
        onRequestListener.OnVerificationSuccess();
        Map<String, Object> map = new HashMap<>();
        map.put("username", phoneNubmber);
        sendRequest(context, "sendCodeByEmail", map, onRequestListener);
    }

    public static void checxEmailCode(Context context, String type, String phoneNubmber, @NonNull OnRequestListener onRequestListener) {
        onRequestListener.OnVerificationSuccess();
        Map<String, Object> map = new HashMap<>();
        map.put("username", phoneNubmber);
        map.put("checkCode ", phoneNubmber);
        map.put("password", phoneNubmber);
        sendRequest(context, "resetPassword", map, onRequestListener);
    }


    public static void registerBySmsCode(Context context, String username, String checkCode, String password, @NonNull OnRequestListener onRequestListener) {
        onRequestListener.OnVerificationSuccess();
        Map<String, Object> map = new HashMap<>();
        map.put("username", username);
        map.put("checkCode", checkCode);
        map.put("password", password);
        sendRequest(context, "register", map, onRequestListener);
    }

    public static void registerBySmsCode(Context context,Map<String, Object> map, @NonNull OnRequestListener onRequestListener) {
        onRequestListener.OnVerificationSuccess();
        sendRequest(context, "register", map, onRequestListener);
    }

    public static void loginByMobilePhone(Context context, String phoneNubmber, String password, @NonNull OnRequestListener onRequestListener) {
        if (!InputVerificationUtils.isEmail(phoneNubmber)) {
            onRequestListener.OnVerificationError(context.getResources().getString(R.string.phonenumber_error));
            return;
        }
        if (TextUtils.isEmpty(password)){
            onRequestListener.OnVerificationError("密码不能为空");
            return;
        }
        onRequestListener.OnVerificationSuccess();
        Map<String, Object> map = new HashMap<>();
        map.put("username", phoneNubmber);
        map.put("password", password);
        loginSendRequest(context, map, onRequestListener);
    }

    public static void forgetPassword(Context context, String phoneNubmber, String password, String smsCode, @NonNull OnRequestListener onRequestListener) {
        if (!InputVerificationUtils.regexPhoneNumber(phoneNubmber)) {
            onRequestListener.OnVerificationError(context.getResources().getString(R.string.phonenumber_error));
            return;
        }
        onRequestListener.OnVerificationSuccess();
        Map<String, Object> map = new HashMap<>();
        map.put("mobilePhoneNumber", phoneNubmber);
        map.put("password", password);
        map.put("smsCode", smsCode);
        sendRequest(context, "forgetPassword", map, onRequestListener);
    }

    /**
     * 开始请求
     */
    private static void sendRequest(Context context, String name, Map<String, Object> map, @NonNull OnRequestListener onRequestListener) {
        Observable.create((ObservableOnSubscribe<Map<String, Object>>) emitter -> AVCloud .callFunctionInBackground(name, map, new FunctionCallback<Map<String, Object>>() {
            @Override
            public void done(Map<String, Object> object, AVException e) {
                if (e == null) {
                    emitter.onNext(object);
                    emitter.onComplete();
                } else {
                    onRequestListener.OnError(context.getResources().getString(R.string.network_error));
                }
            }
        })).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Map<String, Object>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        onRequestListener.onSubscribe(d);
                    }

                    @Override
                    public void onNext(Map<String, Object> object) {
                        if ("0".equals(object.get("error_code") + "") || TextUtils.equals("0",object.get("errorCode")+"")) {
                            onRequestListener.OnSuccer(object);
                        } else {
                            onRequestListener.OnError(object.get("msg") + "");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    /**
     * 登录请求
     * @param context
     * @param map
     * @param onRequestListener
     */
    public static  void loginSendRequest(Context context, Map<String, Object> map, @NonNull OnRequestListener onRequestListener) {
        Observable.create((ObservableOnSubscribe<AVUser>) emitter -> {
            AVUser avUser =  AVUser.logIn(map.get("username")+"",map.get("password")+"");
            if (avUser == null ){
                onRequestListener.OnError(context.getResources().getString(R.string.network_error));
            }else{
                emitter.onNext(avUser);
                emitter.onComplete();
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<AVUser>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        onRequestListener.onSubscribe(d);
                    }

                    @Override
                    public void onNext(AVUser object) {
                        if(object.getMap("result") == null) {
                            Map<String,Object> map = new HashMap<>();
                            map.put("sessionToken",object.getSessionToken());
                            onRequestListener.OnSuccer(map);
                        } else{
                            if ("1".equals(object.getMap("result").get("error_code") + "") || TextUtils.equals("1",object.getMap("result").get("errorCode")+"")) {
                                onRequestListener.OnError((String) object.getMap("result").get("msg"));
                            }else{
                                onRequestListener.OnError("登录失败..");
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        onRequestListener.OnError(e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    public static void changePw(Context context, String username , String checkCode ,String newPw, @NonNull OnRequestListener onRequestListener){
        Map<String, Object> map = new HashMap<>();
        map.put("username", username);
        map.put("checkCode", checkCode);
        map.put("password", newPw);
        sendRequest(context, "resetPassword", map, onRequestListener);
    }

    public static void checkNewVersion(Activity activity,OnRequestListener onRequestListener){
        Map<String, Object> dicParameters = new HashMap<String, Object>();
        dicParameters.put("type", "Android");
        dicParameters.put("version", "v" + AppInfoUtils.getAppVersionName(activity));
        LoginRequestUtils.sendRequest(activity, "A_DxtAppVersion", dicParameters, onRequestListener);
    }
}
